開發 Line Clova無法像 Google Home一樣,直接在 console上作一作,也可以完成一支程式。
一定得要開 cloud function 來實踐才行,建議採用Line的 Clova CEK SDK Nodejs 來做,不過本篇還是先偷懶,直接倒json回去。後面章節再來聊clova cek sdk 可以幫我們做什麼?
如何使用LINE Clova 後台,建置 LINE Clova
#11 介紹
#12 Line Clova Developer Centerβ 環境設定
#13 建立
#14 訓練model
#15 使用 ExtensionサーバーのURL (webhook)串API
#16 送審
如同 #5 我將直接使用 serverless framework 來開 GCP 的cloud function.
不熟 serverless framework 的朋友,請先 follow 這個教學
https://serverless.com/framework/docs/providers/google/guide/quick-start/
hello world 開好正常運作後,直接將下面的code copy到你的index.js上。
exports.parking_clova = (request, response) => {
let getRes = text => {
return {
response: {
outputSpeech: {
type: "SimpleSpeech",
values: {
type: "PlainText",
lang: "ja",
value: text
}
},
card: {},
directives: [],
shouldEndSession: false
}
}
};
console.log("request.body", request.body);
const intent = request.body.request.intent.name;
if (request.body.request.intent.slots.Road === undefined) {
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.status(200).send(JSON.stringify(getRes("この道を手に入れないでください!")));
return
}
if (request.body.request.intent.slots === null) {
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.status(200).send(JSON.stringify(getRes("道路名が必要")));
return
}
const RoadName = request.body.request.intent.slots.Road.value;
var s = "";
callRoadApi(RoadName).then(obj => {
if (obj.length > 0) {
obj.map(i => {
if (intent === "CanParking") {
s += `${i.rd_name} には${i.rd_count}台の駐車スペース `;
} else if (intent === "ParkingPayment") {
translate
.translate(i.tp_name, "ja")
.then(results => {
const translation = results[0];
console.log(`Translation: ${translation}`);
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.status(200).send(JSON.stringify(getRes(translation)));
return;
})
.catch(err => {
console.error('ERROR:', err);
});
}
})
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.status(200).send(JSON.stringify(getRes(s)));
}
})
};
var callRoadApi = (roadName) => {
return new Promise((resolve, reject) => {
console.log("roadName", roadName)
// let path = "http://data.tycg.gov.tw/api/v1/rest/datastore/27d2edc9-890e-4a42-bcae-6ba78dd3c331?format=json";
http.get({ host: "data.tycg.gov.tw", path: "/api/v1/rest/datastore/27d2edc9-890e-4a42-bcae-6ba78dd3c331?format=json&" }, (res) => {
// http.get(path, res => {
let body = ''; // var to store the response chunks
res.on('data', (d) => { body += d; }); // store each response chunk
res.on('end', () => {
let response = JSON.parse(body);
let records = response.result.records;
let r = records.filter((n) => {
if (n.rd_name.indexOf(roadName) > -1) {
return n
}
})
if (r.length > 0) {
resolve(r)
} else {
console.log("fail it")
reject()
}
});
res.on('error', (error) => {
console.log(`Error calling the weather API: ${error}`)
reject();
});
})
})
}
serverless.yaml 加這個
third:
handler: parking_clova
events:
- http: path
再 sls deploy 上去吧
測試吧
搞定。下一章來送審!